package com.popcap.util;

import java.util.*;

/**
 * 
 * ArrayMap
 * 
 * Description:
 * An array with map functionality
 * 
 * @author Evan Salomon evan.salomon@tko-software.com
 * 
 */
public class ArrayMap
{
	private ArrayList m_elements = new ArrayList();

	public class Element
	{
		private String m_strKey;
		private int m_nKeyHash;
		private Object m_value;

		Element(String strKey, Object value)
		{
			m_strKey = strKey;
			m_nKeyHash = strKey.hashCode();
			m_value = value;
		}

		public String getKey()
		{
			return m_strKey;
		}

		public int getKeyHashCode()
		{
			return m_nKeyHash;
		}

		public Object getValue()
		{
			return m_value;
		}
	}

	private class ArrayMapIterator implements Iterator
	{
		private int nPosition = 0;

		public boolean hasNext()
		{
			return nPosition < m_elements.size();
		}

		public Object next()
		{
			return (Element)m_elements.get(nPosition++);
		}

		public void remove()
		{
			throw new UnsupportedOperationException();
		}
	}

	ArrayMap()
	{
	}

	public int size()
	{
		return m_elements.size();
	}

	public boolean put(String strKey, Object value)
	{
		if (containsKey(strKey))
		{
			return false;
		}
		if (strKey != null)
		{
			m_elements.add(new Element(strKey, value));
		}
		return true;
	}

	public int indexOf(String strKey)
	{
		if (strKey == null)
		{
			return -1;
		}

		int nKeyHash = strKey.hashCode();
		for (int i = 0; i < m_elements.size(); i++)
		{
			if (nKeyHash == ((Element)m_elements.get(i)).getKeyHashCode() &&
				strKey.compareTo(((Element)m_elements.get(i)).getKey()) == 0)
			{
				return i;
			}
		}
		return -1;
	}

	public Object get(String strKey)
	{
		int nIndex = indexOf(strKey);
		if (nIndex == -1)
		{
			return null;
		}
		else
		{
			return ((Element)m_elements.get(nIndex)).getValue();
		}
	}

	public String getKey(int nIndex)
	{
		return ((Element)m_elements.get(nIndex)).getKey();
	}

	public Object getValue(int nIndex)
	{
		return ((Element)m_elements.get(nIndex)).getValue();
	}

	public boolean containsKey(String strKey)
	{
		return (indexOf(strKey) != -1);
	}

	public void remove(String strKey)
	{
		int i = indexOf(strKey);
		if (i != -1)
		{
			m_elements.remove(i);
		}
	}

	public void remove(int index)
	{
		m_elements.remove(index);
	}

	public void sort(Comparator c)
	{
		Object[] objects = m_elements.toArray();
		Arrays.sort(objects, c);
		m_elements.clear();
		for (int i = 0; i < objects.length; i++)
		{
			m_elements.add(objects[i]);
		}
	}

	public Iterator iterator()
	{
		return new ArrayMapIterator();
	}
}